'use client'

import { useEffect, useState } from 'react'
import api from '@/lib/api'
import { toast } from 'react-hot-toast'
import { format } from 'date-fns'
import { zhCN } from 'date-fns/locale'
import { Button } from '@/components/ui/button'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Input } from '@/components/ui/input'

interface User {
  id: number
  username: string
  email: string
  role: string
  created_at: string
  name?: string
  phone?: string
  address?: string
  is_active: boolean
}

export default function AdminUsers() {
  const [users, setUsers] = useState<User[]>([])
  const [loading, setLoading] = useState(true)
  const [selectedUser, setSelectedUser] = useState<User | null>(null)
  const [showUserDialog, setShowUserDialog] = useState(false)

  const fetchUsers = async () => {
    try {
      setLoading(true)
      const res = await api.get('/api/admin/users')
      setUsers(res.data)
    } catch (error) {
      toast.error('获取用户列表失败')
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    fetchUsers()
  }, [])

  const handleRoleChange = async (userId: number, role: string) => {
    try {
      await api.put(`/api/admin/users/${userId}/role`, { role })
      toast.success('角色更新成功')
      fetchUsers()
    } catch (error) {
      toast.error('更新失败')
    }
  }

  const handleStatusChange = async (userId: number, isActive: boolean) => {
    try {
      await api.put(`/api/admin/users/${userId}/status`, {
        is_active: isActive
      }, {
        headers: {
          'Content-Type': 'application/json'
        }
      })
      toast.success(isActive ? '用户已启用' : '用户已禁用')
      fetchUsers()
    } catch (error: any) {
      toast.error(error.response?.data?.detail || '操作失败')
    }
  }

  const handleViewDetails = (user: User) => {
    setSelectedUser(user)
    setShowUserDialog(true)
  }

  if (loading) {
    return <div>加载中...</div>
  }

  return (
    <div>
      <h1 className="text-2xl font-bold mb-6">用户管理</h1>

      <div className="bg-white rounded-lg shadow">
        <div className="overflow-x-auto">
          <table className="min-w-full divide-y divide-gray-200">
            <thead>
              <tr>
                <th className="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  用户名
                </th>
                <th className="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  邮箱
                </th>
                <th className="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  角色
                </th>
                <th className="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  状态
                </th>
                <th className="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  注册时间
                </th>
                <th className="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  操作
                </th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {users.map((user) => (
                <tr key={user.id}>
                  <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                    {user.username}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    {user.email}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    <Select
                      value={user.role}
                      onValueChange={(value) => handleRoleChange(user.id, value)}
                    >
                      <SelectTrigger className="w-[100px]">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="user">普通用户</SelectItem>
                        <SelectItem value="admin">管理员</SelectItem>
                      </SelectContent>
                    </Select>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    {user.role === 'admin' ? (
                      <span className="text-gray-500">管理员账户</span>
                    ) : (
                      <Button
                        variant={user.is_active ? "outline" : "destructive"}
                        size="sm"
                        onClick={() => handleStatusChange(user.id, !user.is_active)}
                      >
                        {user.is_active ? '已启用' : '已禁用'}
                      </Button>
                    )}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    {format(new Date(user.created_at), 'yyyy年MM月dd日 HH:mm', { locale: zhCN })}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => handleViewDetails(user)}
                    >
                      查看详情
                    </Button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      <Dialog open={showUserDialog} onOpenChange={setShowUserDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>用户详情</DialogTitle>
          </DialogHeader>
          {selectedUser && (
            <div className="space-y-4">
              <div>
                <label className="text-sm font-medium text-gray-500">用户名</label>
                <Input value={selectedUser.username} readOnly />
              </div>
              <div>
                <label className="text-sm font-medium text-gray-500">邮箱</label>
                <Input value={selectedUser.email} readOnly />
              </div>
              <div>
                <label className="text-sm font-medium text-gray-500">姓名</label>
                <Input value={selectedUser.name || '-'} readOnly />
              </div>
              <div>
                <label className="text-sm font-medium text-gray-500">电话</label>
                <Input value={selectedUser.phone || '-'} readOnly />
              </div>
              <div>
                <label className="text-sm font-medium text-gray-500">地址</label>
                <Input value={selectedUser.address || '-'} readOnly />
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  )
} 